package com.huitone.smspfm.socket.core.net;

import java.lang.reflect.Method;
import java.util.Arrays;

import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.socket.core.handler.AbstractMessageHandler;
import com.huitone.smspfm.socket.protocol.sgip.constant.ErrorCode;
import com.huitone.smspfm.socket.protocol.sgip.message.Message;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.IBody;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.IHead;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**   
* @Title Proxy.java 
* @Package com.huitone.smspfm.socket.core.handler 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年10月15日 下午8:46:17 
* @version V1.0   
*/
public class MessageHandlerProxy implements MethodInterceptor {
	
	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
		
		IHead head = null;
		IBody body = null;
		ExtSocket socket = null;
		Object invokeSuper = null;
		
		if (StringUtils.startsWith(method.getName(), "handle") && args.length == 3 
				&& args[0] instanceof IHead && args[1] instanceof IBody && args[2] instanceof ExtSocket) {
			
			if (args[0] != null) head = (IHead) args[0];
			
			if (args[1] != null) body = (IBody) args[1];
			
			if (args[2] != null) socket = (ExtSocket) args[2];
			
			before(head, body, socket);
			
			invokeSuper = methodProxy.invokeSuper(obj, args);
			
			Method[] declaredMethods = null;
			
			if (socket != null) {
				
				AbstractMessageHandler handler = socket.getHandler();
				
				if (handler != null) {
					declaredMethods = handler.getClass().getDeclaredMethods();
				}
			}
			
			if (declaredMethods == null || !Arrays.asList(declaredMethods).contains(method)) {
				after(head, body, socket);
			}
		}
		
		return invokeSuper;
	}
	
	private void before(IHead head, IBody body, ExtSocket socket) {
		
	}
	
	private void after(IHead head, IBody body, ExtSocket socket) {
		if (socket != null && !socket.isClosed()) {
			socket.response(new Message(head, body), ErrorCode.CODE0);
		}
	}
}
